package com.t194.service.impl;

import com.t194.mapper.PermissionMapper;
import com.t194.pojo.Permission;
import com.t194.service.PermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static java.util.stream.Collectors.toList;

@Service("permissionService")
public class PermissionServiceImpl implements PermissionService{

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public List<String> searchPermCode(String userCode) {
        return permissionMapper.findPermCode(userCode);
    }

    @Override
    public List<Permission> searchPermissionList() {
        List<Permission> list01=permissionMapper.findByParentId(null);
        List<Permission> result= list01.stream().map(perm -> {
            Subject subject= SecurityUtils.getSubject();
            if(subject.isPermitted(perm.getPermCode())){

                List<Permission> list02= permissionMapper.findByParentId(perm.getId());
                if(list02!=null) {
                    for (Permission perm02 : list02) {
                        if (subject.isPermitted(perm02.getPermCode())) {
                            perm.getChildren().add(perm02);
                        }
                    }
                }
                return perm;
            }
            return null;
        }).collect(toList());

        return result;
    }
}
